import { login } from "@/api";
import { useState } from "react";
import { message } from "antd";

function Login(props) {
    let [username, setUsername] = useState("");
    let [password, setPassword] = useState("");
    let { push } = props.history;
    function loginBtn() {
        login(username, password)
            .then(res => {
                if (res.data.state) {
                    localStorage.setItem("token", res.data.token);
                    localStorage.setItem("permission", res.data.permission);
                    localStorage.setItem("userInfo", res.data.userInfo);
                    message.success(res.data.msg);
                    push("/welcome");
                } else {
                    message.error(res.data.msg);
                    setUsername("");
                    setPassword("");
                }
            })
    }

    // 账号框受控
    function unameChange(e) {
        setUsername(e.target.value);
    }

    // 密码框受控
    function pwdChange(e) {
        setPassword(e.target.value);
    }

    return (
        <form style={{
            display: "flex",
            justifyContent: "center",
            alignItems: "center",
            height: "100%"
        }}>
            <div>
                <label>账号：</label>
                <input type="text" value={username} onChange={unameChange} />
            </div>

            <div>
                <label>密码</label>
                <input type="password" value={password} onChange={pwdChange} />
            </div>
            <button onClick={loginBtn}>登录</button>
        </form>
    )
}

export default Login;